# -*-coding:utf-8 -*-
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium import webdriver
import time


class BaiduCrawler:
    def __init__(self, keyword):
        self.url = 'http://news.baidu.com/'
        self.browser = webdriver.Chrome('D://dev//chromedriver_win32//chromedriver.exe')
        self.browser.maximize_window()
        self.wait = WebDriverWait(self.browser, 100)
        self.keyword = keyword
        self.pagesize = 30

    def open(self):
        """
        打开浏览器,并输入查询内容
        """
        self.browser.get(self.url)
        print('执行查询点击')

    def wait_until_list(self):
        """
        等待列表页面加载
        :return:
        """
        handles = self.browser.window_handles
        origin_handle = handles[0]
        WebDriverWait(self.browser, 3600).until(
            EC.presence_of_element_located((By.ID, 'ww'))
        )
        kw = self.wait.until(EC.presence_of_element_located((By.ID, 'ww')))
        kw.send_keys(self.keyword)
        time.sleep(1)
        link = self.browser.find_element_by_id("s_btn_wr")
        link.click()
        handles = self.browser.window_handles
        # print(handles)  # 输出句柄集合

        """
        点击加载更多，将页面完全加载
        """
        new_handle = ''
        for handle in handles:
            if handle != origin_handle:
                new_handle = handle
        self.browser.switch_to.window(new_handle)

    def get_content(self):
        """
        获取页面中的上下文信息，并打印
        :return:
        """
        results = self.browser.find_elements_by_class_name("result-op")
        for i in results:
            print(i.find_element_by_class_name("news-title_1YtI1").text)


if __name__ == '__main__':
    print('开始验证')
    crawler = BaiduCrawler(u'东软集团 战略合作')
    crawler.open()
    crawler.wait_until_list()
    crawler.get_content()
